<template>
  <!-- 添加container类并绑定loaded状态 -->
  <div ref="container" class="container w-full transition-all duration-500" :class="{ 'loaded': isLoaded }">
    <slot v-if="isLoaded" name="content" :loaded="isLoaded" />
    <slot v-else name="skeleton" :loaded="isLoaded" />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, watchEffect } from 'vue';

const props = defineProps({
  // 触发显示的阈值，默认为0.1（元素进入视口10%时触发）
  threshold: {
    type: Number,
    default: 0.1
  },
  // 延迟加载时间（毫秒）
  delay: {
    type: Number,
    default: 0
  },
  // 动画持续时间（毫秒）
  animationDuration: {
    type: Number,
    default: 500
  },
  // 添加rootMargin属性
  rootMargin: {
    type: String,
    default: '0px 0px 0px 0px'
  }
});

const container = ref(null);
const isLoaded = ref(false);
let observer = null;

// 调试信息
const isIntersecting = ref(false);
const entryRatio = ref(0);

const handleIntersect = (entries) => {
  entries.forEach(entry => {
    isIntersecting.value = entry.isIntersecting;
    entryRatio.value = entry.intersectionRatio;

    if (entry.isIntersecting && entry.intersectionRatio >= props.threshold) {
      setTimeout(() => {
        isLoaded.value = true;
        if (observer) {
          observer.unobserve(entry.target);
        }
      }, props.delay);
    }
  });
};

onMounted(() => {
  nextTick(() => {
    if (typeof IntersectionObserver !== 'undefined' && container.value) {
      observer = new IntersectionObserver(handleIntersect, {
        threshold: props.threshold,
        rootMargin: props.rootMargin // 使用属性值
      });
      observer.observe(container.value);

      // 调试信息
      console.log('[ScrollReveal] 组件已挂载，开始观察');
    } else {
      // 浏览器不支持IntersectionObserver时直接显示内容
      isLoaded.value = true;
      console.log('[ScrollReveal] 浏览器不支持IntersectionObserver，直接显示内容');
    }
  });
});

onUnmounted(() => {
  if (observer) {
    observer.disconnect();
    observer = null;
    console.log('[ScrollReveal] 组件已卸载，停止观察');
  }
});

// 调试用：观察加载状态变化
watchEffect(() => {
  console.log(`[ScrollReveal] 加载状态: ${isLoaded.value}, 交叉状态: ${isIntersecting.value}, 交叉比例: ${entryRatio.value}`);
});
</script>

<style scoped>
.skeleton {
  background: linear-gradient(90deg, #1E293B 25%, #2D3748 50%, #1E293B 75%);
  background-size: 200% 100%;
  animation: skeleton-loading 1.5s infinite;
  border-radius: 0.5rem;
}

@keyframes skeleton-loading {
  0% {
    background-position: 200% 0;
  }
  100% {
    background-position: -200% 0;
  }
}

/* 过渡动画 */
.container {
  transition: opacity 0.5s ease, transform 0.5s ease;
}

.container.loaded {
  opacity: 1;
  transform: translateY(0);
}

.container:not(.loaded) {
  opacity: 0;
  transform: translateY(20px);
}
</style>
